import { getShoppingCart } from "@/api/shoppingCart";

const state = {
  shoppingCartList: [],
};

const mutations = {
  SET_SHOPPING_CART_LIST(state, list) {
    state.shoppingCartList = list;
    localStorage.setItem("vuex-shoppingCart", JSON.stringify(list));
  },
  UPDATE_CART_ITEM(state, { userId, productId, quantity }) {
    const userCart = state.shoppingCartList.find((c) => c.user_id === userId);
    if (userCart) {
      const product = userCart.product_list.find(
        (p) => p.product_id === productId
      );
      if (product) {
        product.number = quantity;
        localStorage.setItem(
          "vuex-shoppingCart",
          JSON.stringify(state.shoppingCartList)
        );
      }
    }
  },
  ADD_TO_CART(state, { userId, product }) {
    const userCart = state.shoppingCartList.find((c) => c.user_id === userId);
    const productToAdd = {
      ...product,
      number: 1, // 默认数量为1
      price: product.price,
    };

    if (userCart) {
      const existingProduct = userCart.product_list.find(
        (p) => p.product_id === product.product_id
      );
      if (existingProduct) {
        existingProduct.number += 1;
      } else {
        userCart.product_list.push(productToAdd);
      }
    } else {
      state.shoppingCartList.push({
        user_id: userId,
        product_list: [productToAdd],
        total_price: productToAdd.price,
      });
    }
    localStorage.setItem(
      "vuex-shoppingCart",
      JSON.stringify(state.shoppingCartList)
    );
  },
  CLEAR_CART(state, userId) {
    console.log(state.shoppingCartList, userId);
    state.shoppingCartList.forEach((cart) => {
      if (cart.user_id === userId) {
        cart.product_list = [];
        cart.total_price = 0;
      }
    });
    localStorage.setItem(
      "vuex-shoppingCart",
      JSON.stringify(state.shoppingCartList)
    );
  },
};

const actions = {
  async getShoppingCartList({ commit }) {
    const localData = localStorage.getItem("vuex-shoppingCart");
    if (localData) {
      commit("SET_SHOPPING_CART_LIST", JSON.parse(localData)); // 优先读取本地数据
      return;
    }
    const response = await getShoppingCart();
    commit("SET_SHOPPING_CART_LIST", response.data);
  },
  updateCartItem({ commit }, payload) {
    commit("UPDATE_CART_ITEM", payload);
  },
  addToCart({ commit }, payload) {
    commit("ADD_TO_CART", payload);
  },
  clearCart({ commit }, userId) {
    commit("CLEAR_CART", userId);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
